<?php
namespace addons\paotui\library;

use addons\paotui\service\Config as PaotuiConfig;
use fast\Http;
use think\Log;

class Map{

    public $error;
    public $key;

    public function __construct()
    {
        $this->key = PaotuiConfig::get('amap_key');
    }

    /**
     * 获取附近POI点
     */
    public function getPoiNearby($location,$city){
        $url = "https://restapi.amap.com/v3/place/around?key={$this->key}&types=060102|060602|090101|090206|120200|120301|120302|130104|141201|141202|141203&location={$location}&city={$city}&offset=5&page=1&extensions=base";

        $result = Http::sendRequest($url,[],"get");
        if(empty($msg = $result['msg'])){
            $this->error = '地图服务异常，请联系管理员';
            return false;
        }

        $data = json_decode($msg);
        return $data;
    }

    /**
     * 获取POI
     */
    public function getPoi($keywords,$city){
        $url = "https://restapi.amap.com/v3/place/text?key={$this->key}&keywords={$keywords}&city={$city}&citylimit=true&children=1&offset=8&page=1&extensions=base";
        $result = Http::sendRequest($url,[],"get");
        if(empty($msg = $result['msg'])){
            $this->error = '地图服务异常，请联系管理员';
            return false;
        }

        $data = json_decode($msg);

        return $data;
    }

    public function getCity($lng,$lat){

        $url = "https://restapi.amap.com/v3/geocode/regeo?key={$this->key}&location=".$lng.",".$lat;
      
        $result = Http::sendRequest($url,[],"get");
        //   p($result);die;
        if(empty($msg = $result['msg'])){
            $this->error = '地图服务异常，请联系管理员';
            return false;
        }

        $data = json_decode($msg);
        if(!empty($data->regeocode->addressComponent)){
            return [
                'province'=>$data->regeocode->addressComponent->province,
                'city'=>empty($data->regeocode->addressComponent->city)?$data->regeocode->addressComponent->province:$data->regeocode->addressComponent->city,
                'district'=>$data->regeocode->addressComponent->district,
            ];
        }

        return false;
    }

    /**
     * 获取经纬度的骑行距离
     * @param $origin
     * @param $destination
     * @return false
     */
    public function getCycleDistance($origin,$destination){
        
        $url = "https://restapi.amap.com/v3/distance?origins={$origin}&destination={$destination}&key={$this->key}";
        $result = Http::sendRequest($url,[],"get");

        if(empty($msg = $result['msg'])){
            Log::error('地图服务异常，请联系管理员');
            $this->error = '地图服务异常，请联系管理员';
            return false;
        }

        $data = json_decode($msg);
        if(!empty($data->results[0]->distance)){
            return round($data->results[0]->distance/1000,1);
        }else{
            Log::error($msg);
        }
        return false;
    }

}